package com.xsomnus.network_programming.netty.tcp;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;

import java.nio.charset.StandardCharsets;

/**
 * @author 叶小夏
 * @since 2019-08-21 16:24
 */
public class EchoServerHandler extends ChannelInboundHandlerAdapter {



    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf requestMsg = (ByteBuf) msg;
        System.out.println("(1)requestMsg refCnt = " + requestMsg.refCnt());
        byte[] bytes = new byte[requestMsg.readableBytes()];
        requestMsg.readBytes(bytes);

        String str = new String(bytes, StandardCharsets.UTF_8);
        System.out.println("(2)requestMsg refCnt = " + requestMsg.refCnt() + " receive: " + str);

        ctx.fireChannelRead(Unpooled.copiedBuffer("Client,hello", StandardCharsets.UTF_8));
        System.out.println("(3)requestMsg refCnt = " + requestMsg.refCnt() + " receive: " + str);

        ReferenceCountUtil.release(requestMsg);

        System.out.println("(4)requestMsg refCnt = " + requestMsg.refCnt() + " receive: " + str);
    }
}
